package com.dove.controller;

import com.dove.constant.Constants;
import com.dove.domain.User;
import com.dove.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ProjectName: websocket
 * @Package: com.dove.websocket
 * @ClassName: ${TYPE_NAME}
 * @Description: java类作用描述
 * @Author: dove
 * @CreateDate: 2018/7/22 11:08
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
@Controller
public class webSocketController {
    private static final Logger logger = LoggerFactory.getLogger(webSocketController.class);
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    @RequestMapping("/login")
    public String login(HttpSession session,HttpServletRequest req){
        String username = "user_"+Math.random()*10;
        logger.info("用户登录了建立连接啦===="+session.getId());
        User user = new User();
        user.setUsername(username);
        session.setAttribute(Constants.USER, user);
        return "web";
    }

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(HttpSession session){
        try {
            WebSocketServer.sendInfo("hello  everyone");
            User user = (User)session.getAttribute(Constants.USER);
            WebSocketServer.sendInfoToUser("hello  "+user.getUsername(),session);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
}
